$(function () {
    // 初始化网格
    const grid = GridStack.init({
        cellHeight: 80,
        column: 12,
        margin: 5,
        float: false,
        disableDrag: false,
        disableResize: false,
        acceptWidgets: true,
        alwaysShowResizeHandle: true,
        resizable: {
            handles: 'e, se, s, sw, w'
        },
        minRow: 1
    });

    // 加载初始部件
    loadWidgets();

    // 添加部件按钮点击事件
    $('#add-widget').on('click', function() {
        const type = $('#widget-type').val();
        if (!type) {
            alert('请选择部件类型');
            return;
        }
        
        // 添加到网格中心位置
        const x = Math.floor(grid.width / 3);
        const y = 0;
        
        addWidget(type, x, y);
    });

    // 删除选中部件
    $('#remove-selected').on('click', function() {
        const selected = grid.getSelectedItems();
        if (!selected || selected.length === 0) {
            alert('请先选择要删除的部件');
            return;
        }
        
        // 获取第一个选中部件的ID
        const widgetId = selected[0].el.getAttribute('data-id');
        if (widgetId) {
            removeWidget(widgetId);
        }
    });

    // 保存布局
    $('#save-btn').on('click', function() {
        saveLayout();
    });

    // 新建仪表板
    $('#new-dashboard').on('click', function() {
        if (confirm('确定要创建新的仪表板吗？当前未保存的更改将丢失。')) {
            window.location.href = '/';
        }
    });

    // 加载部件
    function loadWidgets() {
        $.get('/api/widgets', function(data) {
            console.log('Received widgets:', data.widgets);
            grid.removeAll();
            
            data.widgets.forEach(function(widget) {
                const el = document.createElement('div');
                el.className = 'grid-stack-item';
                el.setAttribute('data-id', widget.id);
                
                const content = document.createElement('div');
                content.className = 'grid-stack-item-content';
                content.innerHTML = widget.content;
                
                const removeBtn = document.createElement('span');
                removeBtn.className = 'remove-widget';
                removeBtn.innerHTML = '&times;';
                content.appendChild(removeBtn);
                
                el.appendChild(content);
                
                // 添加到网格
                grid.addWidget(el, {
                    x: widget.x,
                    y: widget.y,
                    w: widget.width,
                    h: widget.height
                });
            });
        }).fail(function(err) {
            console.error("加载部件失败:", err);
        });
    }

    // 添加部件
    function addWidget(type, x, y) {
        $.post('/api/add-widget', {
            type: type,
            x: x,
            y: y
        }, function(response) {
            if (response.status === '部件添加成功') {
                const widget = response.widget;
                const el = document.createElement('div');
                el.className = 'grid-stack-item';
                el.setAttribute('data-id', widget.id);
                
                const content = document.createElement('div');
                content.className = 'grid-stack-item-content';
                content.innerHTML = widget.content;
                
                const removeBtn = document.createElement('span');
                removeBtn.className = 'remove-widget';
                removeBtn.innerHTML = '&times;';
                content.appendChild(removeBtn);
                
                el.appendChild(content);
                
                grid.addWidget(el, {
                    x: widget.x,
                    y: widget.y,
                    w: widget.width,
                    h: widget.height
                });
            }
        }).fail(function(err) {
            console.error("添加部件失败:", err);
            alert('添加部件失败: ' + (err.responseJSON?.error || err.statusText));
        });
    }

    // 删除部件
    function removeWidget(widgetId) {
        $.post('/api/remove-widget', {
            id: widgetId
        }, function(response) {
            if (response.status === '部件删除成功') {
                loadWidgets();
            }
        }).fail(function(err) {
            console.error("删除部件失败:", err);
        });
    }

    // 保存布局
    function saveLayout() {
        const widgets = [];
        grid.getGridItems().forEach(function(item) {
            const node = item.el;
            const content = node.querySelector('.grid-stack-item-content');
            widgets.push({
                id: node.getAttribute('data-id'),
                x: parseInt(item.x),
                y: parseInt(item.y),
                width: parseInt(item.w),
                height: parseInt(item.h),
                content: content.innerHTML.replace(/<span class="remove-widget">×<\/span>/, ''),
                type: content.querySelector('.text-widget') ? 'text' :
                      content.querySelector('.button-widget') ? 'button' :
                      content.querySelector('.switch-widget') ? 'switch' :
                      content.querySelector('.image-widget') ? 'image' : 'chart'
            });
        });

        $.ajax({
            url: '/api/save-layout',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(widgets),
            success: function(response) {
                alert('布局保存成功');
            },
            error: function(err) {
                console.error("保存布局失败:", err);
                alert('保存布局失败: ' + (err.responseJSON?.error || err.statusText));
            }
        });
    }

    // 删除部件按钮事件委托
    $(document).on('click', '.remove-widget', function(e) {
        e.stopPropagation();
        const widgetId = $(this).closest('.grid-stack-item').attr('data-id');
        removeWidget(widgetId);
    });
});